package example;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/books")
public class BookServlet extends HttpServlet {
    private static final Map<String,Book> products=new HashMap<>();
    static{
        products.put("1001",new Book("1001","Java Web 基础版",56.00));
        products.put("1002",new Book("1002","Spring Boot 实战版",68.00));
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        List<Book> books=new ArrayList<>();
        for(Map.Entry<String,Book> entry:products.entrySet()){
            books.add(entry.getValue());
        }
        req.setAttribute("books",books);
        req.getRequestDispatcher("home.jsp").forward(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        String action=req.getParameter("action");
        HttpSession session=req.getSession();
        List<Book> cart=(List<Book>) session.getAttribute("cart");
        if(cart==null){
            cart=new ArrayList<>();
            session.setAttribute("cart",cart);
        }
        if("add".equals(action)){
            String bookId=req.getParameter("id");
            if(bookId==null){
                resp.sendRedirect(req.getContextPath()+"/books");
            }
            cart.add(products.get(bookId));
            session.setAttribute("cart",cart);
            resp.sendRedirect(req.getContextPath()+"/books");
        }
    }
}
